import { defineStore } from 'pinia'
import { TOKEN, USER_INFO } from '@/constant'
import router from '@/router'
import { setAutherRouter } from '@/router/autherRoute'
import { useMenuStore } from './menus'
// import { ElLoading } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: JSON.parse(localStorage.getItem(USER_INFO) || '{}') || {},
  }),
  actions: {
    login(data: any) {
      // 设置token缓存
      localStorage.setItem(TOKEN, data.token)
      localStorage.setItem(USER_INFO, JSON.stringify(data))

      //设置路由
      setAutherRouter(data.rolesMenus)
      //设置菜单
      const menuStore: any = useMenuStore()
      menuStore.setAutherMenus(data.rolesMenus)

      this.userInfo = data || {}
      router.push('/')
    },
    logout() {
      localStorage.removeItem(TOKEN)
      localStorage.removeItem(USER_INFO)
      this.userInfo = {}
      router.push('/login')
    },
  },
})
